package com.geek.javaCource.demo.provider.service;

import com.geek.javaCource.demo.provider.entity.Trace;
import com.geek.javaCource.demo.provider.mapper.AccountMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Create by chenhd on 2021/10/10.
 */
@DubboService
@Service
public class TraceServiceImpl implements TraceService {

    @Autowired
    AccountMapper accountMapper;

    /**
     * 冻结操作，将操作者资金扣除，专项冻结账户
     *
     * @param trace
     * @return
     */
    @Override
    @Transactional
    public boolean tryFrozen(Trace trace) {
        System.out.println("provider begin:" + trace.toString());
        //只扣不增
        int balanceResult = accountMapper.updateBalance(trace.getUserName(), Math.min(trace.getCnyTrace(), 0), Math.min(trace.getUsTrace(), 0));
        //只增不扣，表示"冻结"资金
        int frozenResult = accountMapper.insertFrozen(trace.getUserName(), Math.max(-trace.getCnyTrace(), 0), Math.max(-trace.getUsTrace(), 0), trace.getTraceId());
        if (balanceResult <= 0 || frozenResult <= 0) {
            throw new RuntimeException(trace.getUserName() + " frozen fail.");
        }
        return true;
    }

    /**
     * 提交操作，将冻结账户资金转给转账对象
     *
     * @param trace1
     * @param trace2
     * @return
     */
    @Override
    @Transactional
    public boolean commitTrace(Trace trace1, Trace trace2) {
        System.out.println(trace1.getUserName() + "'s trace confirm");
        int balanceResult = accountMapper.updateBalance(trace1.getTargetUserName(), Math.max(-trace1.getCnyTrace(), 0), Math.max(-trace1.getUsTrace(), 0));
        int frozenResult = accountMapper.deleteFrozen(trace2.getTraceId());
        return balanceResult > 0 && frozenResult > 0;
    }

    /**
     * 回退操作，将冻结账户资金退回给操作账户
     *
     * @param trace
     * @return
     */
    @Override
    @Transactional
    public boolean cancelTrace(Trace trace) {
        System.out.println(trace.getUserName() + "'s trace cancel");
        if (accountMapper.queryFrozen(trace.getTraceId()).size() > 0) {
            //只增不扣
            int balanceResult = accountMapper.updateBalance(trace.getUserName(), Math.max(-trace.getCnyTrace(), 0), Math.max(-trace.getUsTrace(), 0));
            int frozenResult = accountMapper.deleteFrozen(trace.getTraceId());
            return balanceResult > 0 && frozenResult > 0;
        }
        return true;
    }
}
